package com.xhapi.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xhapi.mapper.UserDiaryMapper;
import com.xhapi.pojo.entity.UserDiary;
import com.xhapi.pojo.vo.DiaryVO;
import com.xhapi.service.IUserDiaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户日记表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-08
 */
@Service
@RequiredArgsConstructor
public class UserDiaryServiceImpl extends ServiceImpl<UserDiaryMapper, UserDiary> implements IUserDiaryService {
    private final RestHighLevelClient client;

    /*
     * 基于ES的分页查询
     * */
    public DiaryVO search(Integer userId, String keyword, Integer pageNo, Integer pageSize) throws IOException {
        if (pageNo == null)
            pageNo = 1;
        if (pageSize == null)
            pageSize = 5;
        SearchRequest request = new SearchRequest("diary");
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        // 1.1must 有keyword，对应的是text和title，keyword为空就跳过
        if (StrUtil.isNotBlank(keyword)) {
            bool.must(QueryBuilders.multiMatchQuery(keyword, "title", "text"));
        }
        // 1.2.filter 不参与算分 有 userid，为空也可以跳过（跳过剧情=跳过人生^^
        if (userId != null) {
            bool.filter(QueryBuilders.termQuery("user_id", userId));
        }
        // 上述使用bool查询
        // 2.按时间升序
        request.source().query(bool).sort("diary_date", SortOrder.ASC);
        // 3.pageSize pageNo用于分页
        request.source().from((pageNo - 1) * pageSize).size(pageSize);
        // 4.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        // 5.解析结果
        SearchHits hit = response.getHits();
        long total = hit.getTotalHits().value;
        List<UserDiary> list = new ArrayList<>();
        SearchHit[] hits = hit.getHits();
        for (SearchHit oneHit : hits) {
            String source = oneHit.getSourceAsString();
            UserDiary oneDiary = JSONUtil.toBean(source, UserDiary.class);
            list.add(oneDiary);
        }
        return DiaryVO.builder()
                .list(list)
                .pages(total / (list.size() + 1) + 1)
                .total(total)
                .build();
    }

    /*
     * ES新增日记
     * */
    public void add(UserDiary userDiary) throws IOException {
        IndexRequest request = new IndexRequest("diary");
        request.source(JSONUtil.toJsonStr(userDiary), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }
    /*
     * ES删除日记
     * */
    public void delete(Integer id) throws IOException {
        DeleteRequest request = new DeleteRequest("diary", id.toString());
        client.delete(request, RequestOptions.DEFAULT);
    }
}
